package com.hz.house.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.hz.house.bean.entity.SellManCoinBean;
import com.hz.house.bean.entity.SellManCoinRecordBean;
import com.hz.house.common.BizExcepition;
import com.hz.house.dao.SellManMapper;

/**
 * 置业顾问金币服务
 * @author lfw
 */
@Service
public class SellManCoinService {
	
	@Autowired
	private SellManMapper sellManMapper;
	
	
	/**
	 * 给用户充值金币
	 * @param sellManCustomerId
	 * @param coin 要充值的金币数量
	 */
	@Transactional(rollbackFor = Exception.class)
	public void addCoin(int sellManCustomerId,int coin,String description) throws Exception {
		
		if(coin==0)
			return;
		if(StringUtils.isEmpty(description))
			return;
		//添加金币
		SellManCoinBean c = new SellManCoinBean();
		c.setBalance(coin);
		c.setCreateTime(new Date());
		c.setSellManCustomerId(sellManCustomerId);
		c.setUpdateTime(new Date());
		int x = this.sellManMapper.addCoin(c);
		if(x<1)
			throw new BizExcepition("金币充值失败");
		//先添加记录
		SellManCoinRecordBean r = new SellManCoinRecordBean();
		r.setCoin(coin);
		r.setCreateTime(new Date());
		r.setDescription(description);
		r.setRecordType(2);//2收入
		r.setSellManCustomerId(sellManCustomerId);
		int index =this.sellManMapper.addCoinRecord(r);
		if(index<1)
			throw new Exception("添加金币充值记录失败");
	}
	
	/**
	 * 用户消费金币
	 * @param sellManCustomerId
	 * @param coin
	 * @param description
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor = Exception.class)
	public void minusCoin(int sellManCustomerId,int coin,String description) throws Exception{

		if(coin==0)
			return;
		if(StringUtils.isEmpty(description))
			return;
		//扣减总金币
		int x = this.sellManMapper.minusCoin(sellManCustomerId, coin);
		if(x<1)
			throw new BizExcepition("扣减金币失败，金币不足");
		//先添加记录
		SellManCoinRecordBean r = new SellManCoinRecordBean();
		r.setCoin(coin);
		r.setCreateTime(new Date());
		r.setDescription(description);
		r.setRecordType(1);//1支出
		r.setSellManCustomerId(sellManCustomerId);
		int index =this.sellManMapper.addCoinRecord(r);
		if(index<1)
			throw new Exception("添加扣减金币记录失败");
	
		 
	}
	
}
